package com.epalmpay.service.weixin.impl;

import com.epalmpay.dto.reservationRule.ReservationRuleInDTO;
import com.epalmpay.dto.reservationRule.ReservationRuleOutDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.weixin.IReservationRuleService;
import com.epalmpay.util.Const;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.UtilFun;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Timer;

/**
 * Created by Administrator on 2018/6/5.
 * @author wkf 预约规则service
 */
@Service("ReservationRuleService")
public class ReservationRuleServiceImpl implements IReservationRuleService {

    @Resource
    private ReservationRuleMapper reservationRuleMapper;//预约规则mapper

    @Resource
    private ReservationTimeRuleMapper reservationTimeRuleMapper;//预约规则》时间mapper

    @Resource
    private ReservationConcessionsRuleMapper reservationConcessionsRuleMapper;//预约规则》满减优惠mapper

    @Resource
    private OrderServiceGoodMapper orderServiceGoodMapper;//服务商品订单mapper

    @Resource
    private TradeOfflineMapper tradeOfflineMapper;


    /**
     * 检查指定门店是否存在预约规则，如果存在就返回具体规则信息
     * @param groupId
     * @param shopId
     * @return
     * @throws Exception
     */
    @Override
    public Response checkShopReservation(Long groupId, Long shopId) throws Exception {
        ReservationRuleOutDTO reservationRuleOutDTO = new ReservationRuleOutDTO();

        ReservationRule reservationRule = new ReservationRule();
        reservationRule.setGroupId(groupId);
        reservationRule.setShopId(shopId);
        reservationRule.setStatus(1);//启用状态的规则

        ReservationRule canOrNotReservation = reservationRuleMapper.selectShopReservationCanOrNot(reservationRule);
        reservationRuleOutDTO.setSysTime(canOrNotReservation.getSysTime());//返回当前系统时间
        if(canOrNotReservation != null){
            //如果当前时间处于可预约时间范围内
            if(reservationRuleMapper.selectInOrNotReservationTime(canOrNotReservation.getId()) == null){
                return Response.buildSuccess("-1","当前时间不可预约");
            }
            PropertyCopyUtil.copyProperties(canOrNotReservation,reservationRuleOutDTO);

            //按时段预约，就查询时段表时段信息
            try {
                if(canOrNotReservation.getReservationType().equals(1)){
                    //查询指定规则的时段信息
                    List<ReservationTimeRule> reservationTimeRuleList = reservationTimeRuleMapper.selectTimeByReservationId(canOrNotReservation.getId());
                    if(reservationTimeRuleList != null && reservationTimeRuleList.size()>0){
                        reservationRuleOutDTO.setReservationTimeRuleList(reservationTimeRuleList);
                    }
                }

                //查询指定规则的满减优惠信息
                List<ReservationConcessionsRule> reservationConcessionsRuleList = reservationConcessionsRuleMapper.selectConcessionsByReservationId(canOrNotReservation.getId());
                if(reservationConcessionsRuleList != null && reservationConcessionsRuleList.size()>0){
                    reservationRuleOutDTO.setReservationConcessionsRuleList(reservationConcessionsRuleList);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Response.getError(e.getMessage());
            }

            return Response.getSuccess(reservationRuleOutDTO);
        }else{
            return Response.buildSuccess("-2","该门店没有预约活动");
        }
    }

    @Override
    public Response checkReservationTimeCanOrNot(Long groupId, Long shopId,Long memberId, Long reservationRuleId,
                                                 Integer personCount, String reservationyyyyMMdd, String reservationHHmm,
                                                 String message,Integer reservationType,Long timeRuleId) throws Exception {
        ReservationRuleInDTO reservationRuleInDTO = new ReservationRuleInDTO();
        ReservationRuleOutDTO reservationRuleOutDTO = new ReservationRuleOutDTO();

        //先判断选择的预约时间是否约满
        ReservationRule reservationRule = reservationRuleMapper.selectByPrimaryKey(reservationRuleId);
        if(reservationRule != null){
            //全天预约类型
            if (reservationType.equals(0)) {
                String orderNo;
                //全天类型预约，如果预约剩余单数大于等于1
                if(reservationRule.getReservationRemainNum() != null && reservationRule.getReservationRemainNum()>=1){
                    try {
                        //先占取一单预约
                        ReservationRule reservationRuleIn = new ReservationRule();
                        reservationRuleIn.setId(reservationRuleId);
                        reservationRuleIn.setReservationRemainNum(reservationRule.getReservationRemainNum()-1);
                        reservationRuleMapper.updateByPrimaryKeySelective(reservationRuleIn);

                        //预生成无状态的服务商品订单
                        Date date = new Date();
                        Date yyMmdd = DateUtil.fomatDate(reservationyyyyMMdd,DateUtil.sdfDay);

                        OrderServiceGood orderServiceGood = new OrderServiceGood();
                        orderNo = UtilFun.createOrderNum(Const.CONSUMPTION_VIRTUAL);
                        orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForPay.getType());//订单状态为待付款
                        orderServiceGood.setGmtCreate(date);
                        orderServiceGood.setGroupId(groupId);
                        orderServiceGood.setMemberId(memberId);
                        orderServiceGood.setShopId(shopId);
                        //orderServiceGood.setReservationPersonNum(personCount);//预约人数
                        //orderServiceGood.setReservationDate(yyMmdd);//预约日期
                        //orderServiceGood.setReservationStartTime(Time.valueOf(reservationHHmm+":00"));//预约具体开始时间
                        //orderServiceGood.setReservationEndTime(DateUtil.getTimeAddMinute(reservationHHmm,reservationRule.getReservationInterval()));//预约具体结束时间（废弃）

                        if(Tools.notEmpty(message)){
                          //  orderServiceGood.setLeaveMessage(message);
                        }
                        orderServiceGoodMapper.insertSelective(orderServiceGood);

                        //生成交易记录
                        TradeOffline tradeOffline = new TradeOffline();
                        tradeOffline.setGmtCreate(date);
                        tradeOffline.setGroupId(groupId);
                        tradeOffline.setOrderId(orderNo);
                        tradeOffline.setPayerId(memberId);// 付款者id号
                        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());//付款者类型为7，用户
                        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());// 交易类型
                        tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
                        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());// 交易状态
                        tradeOfflineMapper.insertSelective(tradeOffline);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Response.buildSuccess("-1","可预约判断异常");
                    }
                    ReservationRule result = reservationRuleMapper.selectByPrimaryKey(reservationRuleId);
                    reservationRuleOutDTO.setReservationRemainNum(result.getReservationRemainNum());//返回剩余可预约单数
                    reservationRuleOutDTO.setOrderNo(orderNo);//返回服务商品订单号
                    reservationRuleOutDTO.setShopId(shopId);//返回预约的门店ID
                    reservationRuleOutDTO.setSysTime(reservationRule.getSysTime());//返回系统时间
                    return Response.getSuccess(reservationRuleOutDTO);
                }else{
                    return Response.buildSuccess("-2","今天已约满");
                }
            }else if(reservationType.equals(1)){ //按时间段预约，暂缓开发
                if(timeRuleId == null){
                    return Response.getError("按时段预约，预约时段ID不可为空");
                }

                return Response.getError("按时段预约正在开发，敬请期待");
            }
        }
        return Response.buildSuccess("-3","预约活动不存在");
    }



}
